<template>
  <el-container>
    <el-main class="popup_content">
      <el-form ref="editPromotion" :model="editPromotion" :rules="rules" label-width="90px">
        <el-form-item label="商品" prop="goodsId"  style="width:600px">
            <el-select v-model="productsName" clearable style="width: 100%" value-key="goodsId" @change="productsChange" placeholder="请选择商品"
                       filterable :filter-method="getProductList">
              <el-option v-for="item in productOptions" :label="item.name" :value="item"/>
            </el-select>
        </el-form-item>
        <el-form-item label="促销标题" prop="title" style="width:300px">
          <el-input v-model="editPromotion.title"   placeholder="如消费满100元生效"></el-input>
        </el-form-item>
        <div style="display: flex">
          <el-form-item label="类型" prop="type">
            <span>{{editPromotion.type|watchType}}</span>
          </el-form-item >
        </div>
        <div style="display: flex">
          <el-form-item :label="editPromotion.type|watchMinimumPrice" prop="minimumPrice" v-if="editPromotion.type===7" style="width:300px">
            <el-input v-model="editPromotion.minimumPrice"  type="number"  placeholder="如消费满100元生效"></el-input>
          </el-form-item>
          <el-form-item :label="editPromotion.type|watchlabeltype " prop="amount" style="width:300px"
                        v-if="editPromotion.type===8||editPromotion.type===7||editPromotion.type===10">
            <el-input v-model="editPromotion.amount"  type="number"  placeholder="请输入金额"></el-input>
          </el-form-item>
        </div>
        <el-form-item label="赠品清单" prop="giftType"  v-if="editPromotion.type===11">
          <el-button  type="primary" @click="addCoupon('添加')">添加</el-button>
        </el-form-item>
        <editCoupon  style="width:510px;margin-left: 90px;margin-bottom: 20px"  v-if="editPromotion.type==11" :editCoupon="editPromotion.gifts" :editGiftType="1" :isStatus="0"  ref="editCouponAdd"></editCoupon>
        <div style="display: flex">
          <el-form-item label="商品库存" prop="stock" style="width:300px">
            <el-input  type="number" v-model="editPromotion.stock" placeholder="请输入库存"></el-input>
          </el-form-item>
          <el-form-item label="" prop="firsted" style="width:300px">
            <el-checkbox v-model="editPromotion.firsted">只适用于首单生效</el-checkbox>
          </el-form-item>
        </div>

        <el-form-item label="起始日期" prop="dateTime" style="width:600px">
            <el-date-picker
              v-model="editPromotion.dateTime"
              style="width:100%"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-col :span="12">
            <el-button type="primary" :loading="clicked" @click="updatePromotion('editPromotion')">确 定</el-button>
          </el-col>
        </el-form-item>
      </el-form>

    </el-main>
  </el-container>
</template>

<script>
  import editCoupon from '@/views/promotion/components/editCoupon'
  import {EventBus} from '@/api/eventBus'
  import {find, update} from '../../api/promotion'
  import {list as productList} from '@/api/product'

  export default {
    name: 'productPromotion-edit',
    data() {
      return {

        products: [],
        clicked: false,
        giftTypeList: [],
        productOptions: [],
        productsName:'',
        editPromotion: {
          dateTime: [],
          id: '',
          givenAmount: 0,
          agioRate: 0,
          amount: 0,
          firsted: false,
          goodsId: '',
          giftType: '',
          gifts: [
            {
              promotionId: '',
              giftId: '',
              availableQuantity: 0,
              giftName: '',
              quantity: 0
            }
          ],
          introduction: '',
          minimumPrice: 0,
          modifyDate: '',
          orders: 0,
          stock: 0,
          overlying: false,
          thumbnail: '',
          title: '',
          type: 0,
        },
        rules: {
          type: [{required: true, message: '请输入选择类型', trigger: 'change'},],
          agioRate: [
            {required: true, message: '请输入满减比例', trigger: 'blur'},
          ],
          amount: [
            {required: true, message: '请输入金额', trigger: 'blur'},
          ],
          goodsId: [
            {required: true, message: '请选择促销商品', trigger: 'change'},
          ],
          quantity: [
            {required: true, message: '请输入数量', trigger: 'blur'},
          ],
          minimumPrice: [
            {required: true, message: '请输入数量', trigger: 'blur'},
          ],
          dateTime: [
            {required: true, message: '请输入活动日期', trigger: 'change'},
          ],
          integer: [
            {required: true, message: '请输入优先级', trigger: 'blur'},
          ],
          introduction: [
            {required: true, message: '请输入促销说明', trigger: 'blur'},
          ],
        },
      }
    },
    components:{
      editCoupon
    },
    watch: { // 路由地址不变的情况下,如果id变化则重新获取数据
      $route(newVal, oldVal) {
        console.log(newVal);
        if (newVal.name == 'productPromotion-edit' && newVal.query.id != this.id) {
          this.findPromotion()
        }
      }
    },
    methods: {
      loadCommodity() {
        productList().then(response => {
          response.data.data.forEach(item => {
            let product = {
              name: item.name,
              id: item.id,
              goodsId: item.goodsId
            }
            this.products.push(product)
          })

        })
      },
      addCoupon(){
        this.$refs.editCouponAdd.add()
      },
      findPromotion() {
        var _this = this
        this.editPromotion.id = this.$route.query.id;
        find(this.editPromotion.id).then(response => {
          response.data.promotion.dateTime=[]
          response.data.promotion.dateTime.push(response.data.promotion.beginDate)
          response.data.promotion.dateTime.push(response.data.promotion.endDate)
          this.editPromotion = response.data.promotion;

          this.productsName = response.data.promotion.productName;

          console.log(this.editPromotion)
        })
      },
      // queryProduct (query) { // 查询商品
      //   this.productOptions = []
      //   productList({name: query,pageSize:5}).then(res => {
      //     this.$set(this.$data, 'productOptions', res.data.data)
      //   }).catch(err => {
      //     console.log(err)
      //   })
      // },
      getProductList(query) { // 加载商品
        productList({keyword: query, pageSize: 20,isList:true}).then(res => {
          this.$set(this.$data, 'productOptions', res.data.data)
        }).catch(err => {
          console.log(err)
        })
      },
      updatePromotion(editPromotion) {
        this.$refs[editPromotion].validate((valid) => {
          if (valid) {
            this.clicked = true
            var editPromotion = {
              id: this.editPromotion.id,
              agioRate: this.editPromotion.agioRate,
              amount: this.editPromotion.amount,
              firsted: this.editPromotion.firsted,
              giftType: this.editPromotion.giftType,
              gifts: [],
              beginDate: '',
              endDate: '',
              status: 0,
              goodsId: this.editPromotion.goodsId,
              introduction: this.editPromotion.introduction,
              minimumPrice: this.editPromotion.minimumPrice,
              modifyDate: new Date(),
              orders: this.editPromotion.orders,
              overlying: this.editPromotion.overlying,
              thumbnail: this.editPromotion.thumbnail,
              title: this.editPromotion.title,
              type: this.editPromotion.type,
              stock: this.editPromotion.stock,
            }
            editPromotion.gifts = this.giftTypeList
            if (this.editPromotion.dateTime.length > 0) {
              editPromotion.beginDate = this.editPromotion.dateTime[0];
              editPromotion.endDate = this.editPromotion.dateTime[1]
            }
            if (this.editPromotion.type==11){
              editPromotion.gifts= this.$refs.editCouponAdd.coupons
              editPromotion.giftType=1
            }
            // if (this.editPromotion.type === 7) {
            //   editPromotion.title = '买' + editPromotion.minimumPrice + '件' + '送' + editPromotion.amount
            // } else if (this.editPromotion.type === 8) {
            //   editPromotion.title = editPromotion.amount + '元秒杀'
            // } else if (this.editPromotion.type === 9) {
            //   editPromotion.title = '第二件半价'
            // } else if (this.editPromotion.type === 10) {
            //   editPromotion.title = '新人价:' + editPromotion.amount + '元'
            // }
            console.log(editPromotion)
            update(editPromotion).then(response => {
              this.$store.dispatch('tagsView/delView', this.$route).then(({visitedViews}) => {
                this.$router.push({
                  path: '/productPromotion/list'
                })
              })
              this.clicked = false
              EventBus.$emit('productPromotion-edit', response.data)
            }).catch(error => {
              this.clicked = false
              console.log('error')
            })
          }
        })
      },
      productsChange(val){
        console.log(val)
        this.editPromotion.goodsId = val.goodsId
      }
    },
    created() {
      this.findPromotion()
      // this.loadCommodity()
      this.getProductList('')
    },
    filters: {
      watchType(val) {
        if (val === 7) {
          return '买送'
        } else if (val === 8) {
          return '秒杀'
        } else if (val === 9) {
          return '第二件半价'
        } else if (val === 10) {
          return '新人价'
        } else if (val === 11) {
          return '买赠'
        }
      },
      watchMinimumPrice(val) {
        if (val == 7) {
          return '购买数量'
        }
      },
      watchlabeltype(val) {
        if (val === 7) {
          return '赠送数量'
        } else if (val === 8) {
          return '秒杀价格'
        } else if (val === 10) {
          return '新人价'
        }
      }
    }
  }
</script>

<style scoped>

</style>
